package com.qfedu.entity.course11;

public class InsertSearch {

    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5, 6};
        int left = 0;
        int right = array.length - 1;
        int searchVal = 1;
        System.out.println(search(array, left, right, searchVal));
    }

    public static int search(int[] array, int left, int right, int searchVal) {
        /**
         * 防止数组越界
         */
        if (left > right || searchVal < array[0] || searchVal > array[array.length - 1]) {
            return -1;
        }
        //改进了mid的计算方式
        int mid = left + (right - left) * (searchVal - array[left]) / (array[right] - array[left]);
        int midValue = array[mid];
        if (searchVal > midValue) {
            return search(array, mid + 1, right, searchVal);
        } else if (searchVal < midValue) {
            return search(array, left, mid - 1, searchVal);
        } else {
            return mid;
        }
    }
}